import "./register.scss"
import service from "@@/services/user.service"
import md5 from 'js-md5'
import React, { useCallback, useEffect, useState } from "react"
import NavLayout from "@@/components/layout/nav.layout"
import citytreeConst from "@@/constant/citytree.const"
import Ticon from "@@/t-ui/icon.tui"
import TInput from "@@/t-ui/input.tui"
import { BaseEventOrig, Image, Picker, Text, View, Navigator } from "@tarojs/components"
import { PickerMultiSelectorProps } from "@tarojs/components/types/Picker"
import { useDidHide, useDidShow, useReady, navigateTo } from "@tarojs/taro"
import TButton from "@@/t-ui/button.tui"
import TCheckBox from "@@/t-ui/checkbox.tui"
import TToast from "@@/t-ui/toast.tui"

let timer;//定时器句柄
//密码校验正则 密码中必须包含字母（不区分大小写）、数字6-14位
const pwdRegexp = /(?=.*[0-9])(?=.*[a-zA-Z]).{6,14}/;
const phoneRegexp = /^[0-9]{11,12}$/;
const emailRegexp = /^([0-9A-Za-z]+|[0-9A-Za-z]+\.[0-9A-Za-z]+)(@)([0-9A-Za-z]+\.)([A-z]+)$/;
interface cityData {
  code: string
  name: string
  children?: cityData[]
}
const RegisterPage = () => {
  useEffect(() => { }, [])
  useEffect(() => {
    console.log("useEffect-noData")
  })
  useDidShow(() => {
    console.log("useDidShow")
  })
  useDidHide(() => {
    console.log("useDidHides")
  })

  useReady(() => {
    console.log("useReady")
  })
  const [name, setName] = useState<string>("")//用户名
  const [mobile, setMobile] = useState<string>("")//手机号
  const [email, setEmail] = useState<string>("")//邮箱
  const [company, setCompany] = useState<string>("")//单位信息
  const [passWord, setPassWord] = useState<string>("")//用户密码
  const [verificationCode, setVerificationCode] = useState<string>("")//验证码
  const [time, setTime] = useState<number>(0)//验证码倒计时

  const [cityValue, setCityValue] = useState<(number)[]>([0, 0, 0])
  const [rangeValue, setRangeValue] = useState<number[]>([0, 0, 0])

  const [remember, setRemember] = useState<string[]>([])//是否同意
  const [isOpened, setIsOpened] = useState<boolean>(false)//轻提示开关
  const [toastMsg, setToastMsg] = useState<string>("")//轻提示内容
  const [pwdFail, setPwdFail] = useState<boolean>(false)//提示密码错误

  const onColumnChange = useCallback(
    (e: BaseEventOrig<PickerMultiSelectorProps.onColumnChangeEvnetDetail>) => {
      const { column, value } = e.detail
      const newData = [...rangeValue]
      for (let index = column; index < newData.length; index++) {
        newData.splice(index, 1, index === column ? value : 0)
      }
      console.log(newData)
      setRangeValue(newData)
    },
    [rangeValue]
  )
  const onChange = useCallback((e: BaseEventOrig<PickerMultiSelectorProps.onChangeEventDetail>) => {
    const { value } = e.detail
    // console.log(value)
    setCityValue(value)
  }, [])

  const openToast = (str: string) => {
    setToastMsg(str)
    setIsOpened(true)
    setTimeout(() => {
      setIsOpened(false)
    }, 500)
  }
  const getItems = useCallback(
    (data: cityData[], index: number, result: (cityData | null)[]): (cityData | null)[] => {
      return index < cityValue.length
        ? cityValue[index] !== null
          ? data[cityValue[index]].children
            ? getItems(
              data[cityValue[index]].children!,
              index + 1,
              result.concat([
                {
                  name: data[cityValue[index]].name,
                  code: data[cityValue[index]].code
                }
              ])
            )
            : result.concat([
              {
                name: data[cityValue[index]].name,
                code: data[cityValue[index]].code
              }
            ])
          : getItems([], index + 1, result.concat([null]))
        : result
    },
    [cityValue]
  )

  //发送验证码
  const sendVerificationCode = () => {
    if (TARO_ENV === "h5") {
      service.sendVerificationCode({ mobile, type: 0 }).then(res => {
        if (res.code === 200) {
          countDown();
        } else {
          openToast(res.msg)
          return false
        }
      })
    }
  }
  //倒计时方法
  const countDown = () => {
    let num = 60;
    setTime(num)
    const reduce = () => {
      if (num > 0) {
        timer = setTimeout(() => {
          num -= 1
          setTime(num)
          reduce();
        }, 1000)
      } else {
        clearTimeout(timer)
      }
    }
    reduce()
  }
  //注册
  const register = async () => {
    if (TARO_ENV === "h5") {
      // console.log(cityValue)
      // console.log(citytreeConst[cityValue[0]])
      // console.log(citytreeConst[cityValue[0]].children[cityValue[1]])
      // console.log(citytreeConst[cityValue[0]].children[cityValue[1]].children[cityValue[2]])
      if (!emailRegexp.test(email)) {
        openToast("邮箱格式不正确！")
        return false
      }
      if (!phoneRegexp.test(mobile)) {
        openToast("请输入11-12位为数字的手机号")
        return false
      }

      if (!verificationCode) {
        openToast("验证码不能为空")
        return false
      }
      if (!remember[0]) {
        openToast("请勾选下方并接受用户协议")
        return false
      }

      let isRegister = false;
      await service.isRegister({ mobile }).then(res => {
        if (res.code !== 200) {
          isRegister = true
          openToast(res.msg)
        }
      })
      if (isRegister) {
        return false
      }
      const params = {
        name,
        mobile,
        email,
        company,
        passWord: md5(passWord),
        verificationCode,
        province: citytreeConst[cityValue[0]]?.code,
        provinceName: citytreeConst[cityValue[0]]?.name,
        city: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.code,
        cityName: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.name,
        area: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.children[cityValue[2]].code,
        areaName: citytreeConst[cityValue[0]]?.children[cityValue[1]]?.children[cityValue[2]].name,
        source: 3,
        hallId: 23
      }
      service.register(params).then(res => {
        if (res.code === 200) {
          if (TARO_ENV === "h5") {
            openToast("你已成功注册");
            navigateTo({
              url: "/pages/login/login"
            })
          }
        }
      })
    }
  }


  return (
    <NavLayout border leftIconType="chevron-left" color="#141414" id="RegeditPage">
      <View className="logo-box">
        <Image className="logo" src={require("@@/assets/img/logo.png")} />
      </View>
      <View className="regedit">
        <View className="title">欢迎注册</View>
        <View className="form">
          <View className="input-item">
            <TInput border={false} name="name" type="text" placeholder="请输入姓名" onChange={v => {
              setName(v)
              return v
            }} />
          </View>
          <View className="input-item">
            <TInput border={false} name="email" type="text" placeholder="请输入邮箱" onChange={v => {
              setEmail(v)
              return v
            }} />
          </View>
          <View className="input-item">

            <TInput
              border={false}
              name="company"
              type="text"
              placeholder="请输入单位信息"
              onChange={v => {
                setCompany(v)
                return v
              }}
            />
          </View>
          <Picker
            mode="multiSelector"
            range={[
              citytreeConst,
              citytreeConst[rangeValue[0]].children,
              citytreeConst[rangeValue[0]].children[rangeValue[1]].children
            ]}
            rangeKey="name"
            value={rangeValue}
            onChange={onChange}
            onColumnChange={onColumnChange}
          >
            <View className="select-city">
              {getItems(citytreeConst, 0, []).map((m, i) => {
                return (
                  <View className="input-item" key={i}>
                    <Text className="city-name">{m ? m.name : `选择${["省", "市", "区"][i]}`}</Text>
                    <Ticon value="chevron-down" size={0} />
                  </View>
                )
              })}
            </View>
          </Picker>
          <View className="input-item">
            <TInput border={false} name="mobile" type="text" placeholder="请输入手机号" onChange={v => {
              setMobile(v)
              return v
            }} />
          </View>
          <View className="verify-code-box">
            <View className="input-item verify-code">
              <TInput
                border={false}
                name="verificationCode"
                type="text"
                placeholder="验证码"
                onChange={v => {
                  setVerificationCode(v)
                  return v
                }}
              />
            </View>
            {
              time > 0 ? <View className={"send"}>{time}</View> : <View className={"send"} onClick={sendVerificationCode}>发送验证码</View>
            }
          </View>
          <View className="input-item">
            <TInput border={false} name="passWord" type="password" placeholder="请输入密码" onChange={v => {
              if (v && !pwdRegexp.test(v)) {
                setPwdFail(true)
              } else {
                setPwdFail(false)
                setPassWord(v)
              }
              return v
            }} />
          </View>
          {
            pwdFail && <View className={"msg_box"}>
              <View className={'warning_logo'}><Image mode={"aspectFit"} src={require('@@/assets/img/warning.png')} /></View>
              <Text>长度为8-14个字符，字母/数字以及标点符号至少包含2种</Text>
            </View>
          }
          <View className="form-btn">
            <TButton type="primary" onClick={register}>注册</TButton>
          </View>
          <View className="form-remember">
            <TCheckBox
              options={[{ value: "remember", label: "" }]}
              onChange={e => {
                setRemember(e)
              }}
            />
            <View className="remember-txt">
              我已阅读<Navigator className="link" url={"/pages/agree/agree"}>《注册协议》</Navigator>与<Navigator className="link" url={"/pages/copyright/copyright"}>《隐私协议》</Navigator>
            </View>
          </View>
        </View>

        <View className="bg" />
        <TToast isOpened={isOpened} text={toastMsg} />
      </View>
    </NavLayout>
  )
}
export default RegisterPage
